package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.utils.CommonUtils.selectProductMaintenanceTime;
import static com.jsjosem.aftersales.utils.CommonUtils.selectTime;
import static com.jsjosem.aftersales.utils.CommonUtils.setSpinnerAdapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.ProductTypeAdapter;
import com.jsjosem.aftersales.api.DepartmentsApi;
import com.jsjosem.aftersales.api.ProductApi;
import com.jsjosem.aftersales.api.ProductTypeApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.request.ProductRequest;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.CustomerResponse;
import com.jsjosem.aftersales.data.response.DepartmentsResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.data.response.ProductTypeResponse;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.request.FileRequest;
import com.jsjosem.aftersales.utils.GetFilePathFromUri;
import com.jsjosem.aftersales.utils.ImmUtils;
import com.jsjosem.aftersales.utils.PermissionUtils;
import com.jsjosem.aftersales.utils.ScreenSizeUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

public class CreateProductActivity extends AppCompatActivity {

    private EditText customerNameET, detailsAddressET, productNameET, productTypeET, purchaseDateET, warrantyDateStartET, warrantyDateEndET, checkDateET;
    private ImageView icBack;
    private Spinner serviceNetworkSp;
    private ProductTypeResponse productType;
    private ConstraintLayout createProductLayout, automaticCalculationLayout, manualCalculationLayout, attachmentLayout;
    private RadioButton automaticCalculationRadio, manualCalculationRadio;
    private Intent intent;
    private Dialog loadingDialog;
    private Button saveBtn;
    private View purchaseDateView, warrantyDateStartView, warrantyDateEndView, productTypeView, checkDateView;
    private CustomerResponse customer;
    private LinearLayout warrantyInfoLay;
    private TextView warrantyTypeTv, warrantyDateTv, automaticCalculationTipTv, warrantyStatusTv, attachmentTv;
    private List<DepartmentsResponse> deptList = new ArrayList<>();
    private List<ProductTypeResponse> productTypeList = new ArrayList<>();
    private Retrofit mRetrofit = RetrofitClient.getInstance();
    private Boolean flag = true;
    private File file;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_product);
        initView();
        initData();
        setRadioCheckListener();
        getServiceNetwork();

        ImmUtils.setCloseKeyboard(createProductLayout, this);
        ImmUtils.setEditTextHintFontSize(customerNameET, 14, "请选择客户");
        ImmUtils.setEditTextHintFontSize(productNameET, 14, "清输入产品名称");
        ImmUtils.setEditTextHintFontSize(productTypeET, 14, "请选择产品类型");
        ImmUtils.setEditTextHintFontSize(purchaseDateET, 14, "请输入购买日期");
        ImmUtils.setEditTextHintFontSize(warrantyDateStartET, 14, "请选择质保开始日期");
        ImmUtils.setEditTextHintFontSize(warrantyDateEndET, 14, "请选择质保结束日期");
        ImmUtils.setEditTextHintFontSize(checkDateET, 14, "请选择检查日期");
        ImmUtils.setEditTextHintFontSize(detailsAddressET, 14, "请输入安装地址");

        purchaseDateView.setOnClickListener(v -> {
            selectTime(this, purchaseDateET);
        });

        checkDateView.setOnClickListener(v -> {
            selectTime(this, checkDateET);
        });

        attachmentLayout.setOnClickListener(v -> {
            //选择文件
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1);
        });

        warrantyDateStartView.setOnClickListener(v -> {
            if (productType != null) {
                if (flag) {
                    String type = productType.getWarrantyStartUnit();
                    int count = Integer.parseInt(productType.getWarrantyCycleCount().toString());
                    if (type.equals("month")) {
                        selectProductMaintenanceTime(this, warrantyDateStartET, warrantyDateEndET, count, true);
                    } else {
                        selectProductMaintenanceTime(this, warrantyDateStartET, warrantyDateEndET, (count * 12), true);
                    }
                } else {
                    selectTime(this, warrantyDateStartET);
                }
            } else {
                Toast.makeText(this, "请先选择产品类型", Toast.LENGTH_SHORT).show();
            }

        });

        warrantyDateEndView.setOnClickListener(v -> {
            if (productType != null) {
                if (flag) {
                    String type = productType.getWarrantyStartUnit();
                    int count = Integer.parseInt(productType.getWarrantyCycleCount().toString());
                    if (type.equals("month")) {
                        selectProductMaintenanceTime(this, warrantyDateStartET, warrantyDateEndET, count, false);
                    } else {
                        selectProductMaintenanceTime(this, warrantyDateStartET, warrantyDateEndET, (count * 12), false);
                    }
                } else {
                    selectTime(this, warrantyDateEndET);
                }
            } else {
                Toast.makeText(this, "请先选择产品类型", Toast.LENGTH_SHORT).show();
            }
        });

        productTypeView.setOnClickListener(v -> {
            productTypeDialog();
        });

        saveBtn.setOnClickListener(v -> {
            ProductRequest productRequest = new ProductRequest();
            if (customerNameET.getText().toString().equals("")) {
                Toast.makeText(this, "请选择客户", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setCustomerId(Long.valueOf(customer.getId().toString()));
            }
            if (productNameET.getText().toString().equals("")) {
                Toast.makeText(this, "请输入产品名称", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setName(productNameET.getText().toString());
            }
            if (productTypeET.getText().toString().equals("")) {
                Toast.makeText(this, "请选择产品类型", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setTypeId(Long.valueOf(productType.getId().toString()));
            }
            if (purchaseDateET.getText().toString().equals("")) {
                Toast.makeText(this, "请输入购买日期", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setDateBuy(purchaseDateET.getText().toString());
            }
            if (warrantyDateStartET.getText().toString().equals("")) {
                Toast.makeText(this, "请选择质保开始日期", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setWarrantyStart(warrantyDateStartET.getText().toString());
            }
            if (warrantyDateEndET.getText().toString().equals("")) {
                Toast.makeText(this, "请选择质保结束日期", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setWarrantyEnd(warrantyDateEndET.getText().toString());
            }
            if (checkDateET.getText().toString().equals("")) {
                Toast.makeText(this, "请选择检查日期", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setDateCheck(checkDateET.getText().toString());
            }
            if (detailsAddressET.getText().toString().equals("")) {
                Toast.makeText(this, "请输入安装地址", Toast.LENGTH_SHORT).show();
                return;
            } else {
                productRequest.setmInstallAddress(detailsAddressET.getText().toString());
            }
            productRequest.setWarrantyType(productType.getWarrantyStartUnit());
            if (file != null) {
                uploadFile(productRequest);
            }else{
                createProduct(productRequest);
            }
        });

        icBack.setOnClickListener(v -> finish());

        customerNameET.setText(customer.getName());
    }

    protected void onResume() {
        super.onResume();
        if (PermissionUtils.isPermissionGranted(this)) {
            Log.i("PERMISSION", "请求权限成功");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission", "授权失败！");
                    // 授权失败，退出应用
                    this.finish();
                    return;
                }
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 1) {//是否选择，没选择就不会继续
            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
            String path = GetFilePathFromUri.getFileAbsolutePath(this, uri);
            file = new File(path);
            attachmentTv.setVisibility(View.VISIBLE);
            attachmentTv.setText(file.getName());
        }
    }

    private void initView() {
        customerNameET = findViewById(R.id.customer_name);
        productNameET = findViewById(R.id.product_name);
        productTypeET = findViewById(R.id.product_type);
        purchaseDateET = findViewById(R.id.purchase_date);
        warrantyDateStartET = findViewById(R.id.warranty_date_start);
        warrantyDateEndET = findViewById(R.id.warranty_date_end);
        icBack = findViewById(R.id.img_back);
        createProductLayout = findViewById(R.id.create_product_lay);
        automaticCalculationLayout = findViewById(R.id.automatic_calculation);
        manualCalculationLayout = findViewById(R.id.manual_calculation);
        automaticCalculationRadio = findViewById(R.id.automatic_calculation_radio);
        manualCalculationRadio = findViewById(R.id.manual_calculation_radio);
        purchaseDateView = findViewById(R.id.purchase_date_view);
        warrantyDateStartView = findViewById(R.id.warranty_date_start_view);
        warrantyDateEndView = findViewById(R.id.warranty_date_end_view);
        productTypeView = findViewById(R.id.product_type_view);
        loadingDialog = new Dialog(this, R.style.normal_dialog_style);
        warrantyInfoLay = findViewById(R.id.warranty_info_lay);
        warrantyTypeTv = findViewById(R.id.warranty_type);
        warrantyDateTv = findViewById(R.id.warranty_date);
        automaticCalculationTipTv = findViewById(R.id.automatic_calculation_tip);
        checkDateView = findViewById(R.id.check_date_view);
        checkDateET = findViewById(R.id.check_date);
        serviceNetworkSp = findViewById(R.id.service_network);
        attachmentLayout = findViewById(R.id.attachment);
        attachmentTv = findViewById(R.id.attachment_tv);
        saveBtn = findViewById(R.id.save);
        detailsAddressET = findViewById(R.id.details_address);
//        warrantyStatusTv = findViewById(R.id.warranty_status);
    }

    private void initData() {
        automaticCalculationRadio.setChecked(true);
        intent = getIntent();
        customer = (CustomerResponse) intent.getSerializableExtra("customer");
        customerNameET.setText(customer.getName());
    }

    private void setRadioCheckListener() {
        automaticCalculationLayout.setOnClickListener(v -> {
            automaticCalculationRadio.setChecked(true);
            manualCalculationRadio.setChecked(false);
            flag = true;
        });

        manualCalculationLayout.setOnClickListener(v -> {
            automaticCalculationRadio.setChecked(false);
            manualCalculationRadio.setChecked(true);
            flag = false;
        });

        automaticCalculationRadio.setOnClickListener(v -> {
            automaticCalculationRadio.setChecked(true);
            manualCalculationRadio.setChecked(false);
            flag = true;
        });

        manualCalculationRadio.setOnClickListener(v -> {
            automaticCalculationRadio.setChecked(false);
            manualCalculationRadio.setChecked(true);
            flag = false;
        });
    }

    private void getServiceNetwork() {
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> request = new AsyncRequest<>();
        request.sendRequest(getDepartments, res -> {
            deptList.addAll(res.getData());
            //将deptList转换为String类型的数组
            String[] deptNameList = new String[deptList.size()];
            for (int i = 0; i < deptList.size(); i++) {
                deptNameList[i] = deptList.get(i).getName();
            }
            setSpinnerAdapter(this, serviceNetworkSp, deptNameList, 0);

        }, err -> {
            Toast.makeText(this, err.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    private void getProductType(ProductTypeAdapter adapter) {
        ProductTypeApi productTypeApi = mRetrofit.create(ProductTypeApi.class);
        Call<PageResponse<ProductTypeResponse>> productTypes = productTypeApi.getProductTypes(1, 9999);
        AsyncRequest<PageResponse<ProductTypeResponse>> request = new AsyncRequest<>();
        request.sendRequest(productTypes, res -> {
            productTypeList.addAll(res.getData());
            adapter.notifyDataSetChanged();
            loadingDialog.dismiss();
        }, err -> {
            Toast.makeText(this, err.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    private void productTypeDialog() {
        View view = View.inflate(this, R.layout.dialog_product_type, null);
        Dialog dialog = createDialog(view);
        dialog.setContentView(view);
        ListView listView = view.findViewById(R.id.product_list_list);
        ProductTypeAdapter adapter = new ProductTypeAdapter(this, R.layout.my_simple_item_list, productTypeList);
        listView.setAdapter(adapter);
        if (productTypeList.size() == 0) {
            loadingShow();
            getProductType(adapter);
        }
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            productTypeET.setText(productTypeList.get(position).getName());
            productType = productTypeList.get(position);
            warrantyInfoLay.setVisibility(View.VISIBLE);
            if (productType.getWarrantyStartUnit().equals("month")) {
                warrantyTypeTv.setText("月");
            } else {
                warrantyTypeTv.setText("年");
            }
            warrantyDateTv.setText(productType.getWarrantyCycleCount().toString());
            automaticCalculationTipTv.setVisibility(View.GONE);
            dialog.dismiss();
        });
        dialog.show();
    }

    private void loadingShow() {
        loadingDialog = new Dialog(this, R.style.normal_dialog_style);
        View loadingView = View.inflate(this, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

    private Dialog createDialog(View dialogView) {
        Dialog dialog = new Dialog(this, R.style.background_darkens_dialog_style);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        return dialog;
    }

    private void createProduct(ProductRequest productRequest) {
        ProductApi productApi = mRetrofit.create(ProductApi.class);
        Call<BaseResponse<Void>> createProduct = productApi.createProduct(productRequest);
        AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
        request.sendRequest(createProduct, res -> {
            loadingDialog.dismiss();
            Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show();
            finish();
        }, err -> {
            loadingDialog.dismiss();
            Toast.makeText(this, err.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    private void uploadFile(ProductRequest productRequest){
        FileRequest request = new FileRequest();
        loadingShow();
        request.uploadFile(file, res -> {
            productRequest.setAttachment(res.getData().getPath());
            createProduct(productRequest);
        }, err -> {
            System.out.println(err.toString());
        });
    }
}